import Vue from 'vue'
import axios from 'axios'
import settle from 'axios/lib/core/settle'
import buildURL from 'axios/lib/helpers/buildURL'
import JSONbig from '@/utils/jsonBigint/index.js';
import projectConfig from '../core/config'
import { getObjectFromSessionStorage } from '@/utils';

axios.defaults.adapter = config => {
	return new Promise((resolve, reject) => {
		uni.request({
			method: config.method.toUpperCase(),
			url: (config.baseURL ? config.baseURL : '') + buildURL(config.url, config.params, config.paramsSerializer),
			header: {
				'Content-Type': 'application/json; charset=utf-8',
				'deviceType': '4',
				'Authorization': uni.getStorageSync('token'),
				'MenuId': getObjectFromSessionStorage('currentMenuId')
			},
			data: config.data,
			dataType: 'string',
			responseType: 'text',
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}

const service = axios.create({
	baseURL: projectConfig.baseUrl, // url = base url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000, // request timeout
	crossDomain: true,
	headers: {
		'Content-Type': 'application/json; charset=utf-8',
		'deviceType': '4',
		'Authorization':uni.getStorageSync('token'),
		'MenuId': getObjectFromSessionStorage('currentMenuId')
	},
	responseType: 'text',
	transformResponse: [
		function(data) {
			if (typeof data === 'string') {
				const JSONbigString = new JSONbig({
					storeAsString: true
				});
				return JSONbigString.parse(data);
			} else {
				return data;
			}
		}
	]
})

const err = (error) => {
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  const data = response.data
	if (!data) {
		Vue.prototype.$u.toast( '网络请求错误')
		return Promise.reject(data)
	}else if (data && !data.success){
		Vue.prototype.$u.toast(data.errorMessage || '网络请求错误')
		return Promise.reject(data)
	}

  return data.data === undefined ? {} : data.data
},err)

export default service